package com.huc.rest.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.UnknownHostException;

public class WebUtils {

    private static final int BUFFERSIZE = 8196;
    private static final String CHARSETNAME = "UTF-8";

    public static WebUtils getInstance(){
        return new WebUtils();
    }

    public String getLocalHost() {
        try {
            return InetAddress.getLocalHost().toString();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return "";
    }

    public String getHeader(HttpServletRequest request, String name) {
        return request.getHeader(name);
    }

    public String getHeaderDecode(HttpServletRequest request, String name) {
        try{
            return URLDecoder.decode(getHeader(request, name), "UTF-8");
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        System.out.println(URLDecoder.decode("user_login","UTF-8"));
    }


    //关闭流信息
    public void closeBufferedInputStream(BufferedInputStream bufferedInputStream) {

        if(bufferedInputStream != null) {
            try {
                bufferedInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            bufferedInputStream = null;
        }
    }

    public void closeInputStream(InputStream inputStream) {

        if(inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            inputStream = null;
        }
    }

    public String generateContent(InputStream inputStream) {

        if (inputStream == null) {
            return null;
        }

        BufferedInputStream bufferedInputStream = null;

        StringBuffer content = new StringBuffer();

        try {
            byte[] buffer = new byte[BUFFERSIZE];
            int count = 0;

            bufferedInputStream = new BufferedInputStream(inputStream, BUFFERSIZE);

            while ((count = bufferedInputStream.read(buffer)) != -1) { // >0
                content.append(new String(buffer, 0, count, CHARSETNAME));
            }

            buffer = null;

            return content.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            closeBufferedInputStream(bufferedInputStream);
            closeInputStream(inputStream);
        }
    }

    public void responseContent(HttpServletResponse response, String rescontent) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");
        response.setContentLength(rescontent.length());

        OutputStream outputstream = null;
        BufferedOutputStream bufferedOutputStream = null;

        try {
            outputstream = response.getOutputStream();
            bufferedOutputStream = new BufferedOutputStream(outputstream, BUFFERSIZE);

            bufferedOutputStream.write(rescontent.getBytes("UTF-8"));

            bufferedOutputStream.flush();

            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeBufferedOutputStream(bufferedOutputStream);
            closeOutputStream(outputstream);
        }
    }
    public void closeBufferedOutputStream(BufferedOutputStream bufferedOutputStream) {

        if(bufferedOutputStream != null) {
            try {
                bufferedOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            bufferedOutputStream = null;
        }
    }
    public void closeOutputStream(OutputStream outputStream) {

        if(outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            outputStream = null;
        }
    }
    public void closeFileInputStream(FileInputStream fileInputStream) {

        if(fileInputStream != null) {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            fileInputStream = null;
        }
    }

    public void flush(BufferedOutputStream bufferedOutputStream) {

        try {
            bufferedOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void flush(HttpServletResponse response) {

        try {
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String response(String resfilename) {

        FileInputStream fileInputStream  = null;
        BufferedInputStream bufferedInputStream = null;

        StringBuffer rescontent = new StringBuffer();

        try {
            fileInputStream = new FileInputStream(resfilename);
            bufferedInputStream = new BufferedInputStream(fileInputStream, BUFFERSIZE);

            int count = 0;
            byte[] buffer = new byte[BUFFERSIZE];

            while ((count = bufferedInputStream.read(buffer)) != -1) {
                rescontent.append(new String(buffer, 0, count, "UTF-8"));
            }

            buffer = null;

            return rescontent.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        } finally {
            closeBufferedInputStream(bufferedInputStream);
            closeFileInputStream(fileInputStream);
        }
    }

    public String getDefaultRescontent(String format) {

        if(!format.equalsIgnoreCase("JSON")) {
            format = "XML";
        }

        return 100002 + format.toLowerCase();
    }

//    public void operatelog(ServiceCoreVO scvo) {
//
//        new OperatelogThread(scvo).start();
//    }

//    private class OperatelogThread extends Thread {
//        APIOperatelogVO vo = null;
//
//        private OperatelogThread(ServiceCoreVO scvo) {
//            vo = new APIOperatelogVO();
//            vo.setOperateLogno(scvo.getOperateLogno());
//            vo.setRequestTime(scvo.getRequestTime());
//            vo.setCompleteTime(TimeUtils.getSysTime());
//            vo.setIp(scvo.getIp());
//            vo.setServiceType(scvo.getServiceType());
//            vo.setRequestUrl(scvo.getRequestUrl());
//            vo.setBean(scvo.getBean());
//            vo.setMethod(scvo.getMethod());
//            vo.setAccessId(scvo.getAccessId());
//            vo.setAccessKey(scvo.getAccessKey());
//            vo.setCode((scvo.getCode()==0)?100000:scvo.getCode());
//            vo.setException((scvo.getCode()==0)?"":PropertiesUtils.getMessage(scvo.getCode()+""));
//            vo.setContent(content(scvo));
//            scvo = null;
//        }

//        private String content(ServiceCoreVO scvo){
//            StringBuffer content = new StringBuffer();
//            if(ValidatorUtils.isNotEmpty(scvo.getFormat())) {
//                content.append(";format->" + StringUtils.getInstance().nullToStrTrim(scvo.getFormat()));
//            }
//            if(scvo.getReqLength() > 0) {
//                content.append(";reqlength->" + scvo.getReqLength());
//            }
//            if(ValidatorUtils.isNotEmpty(scvo.getSign())) {
//                content.append(";sign->" + StringUtils.getInstance().nullToStrTrim(scvo.getSign()));
//            }
//            if(ValidatorUtils.isNotEmpty(scvo.getReqContentMd5())) {
//                content.append(";reqcontentmd5->" + StringUtils.getInstance().nullToStrTrim(scvo.getReqContentMd5()));
//            }
//            if(ValidatorUtils.isNotEmpty(scvo.getReqContent())){
//                content.append(";content->" + StringUtils.getInstance().nullToStrTrim(scvo.getReqContent()));
//            }
//            return content.length() > 0 ? content.substring(1) : content.toString();
//        }

//        public void run() {
//            ApiLogDao logDao = (ApiLogDao)ContextUtils.getBean("apiLogDao");
//            logDao.addLogInfo(vo);
//        }

//    }
}
